package gw.com.android.presenter.http;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.interfaces.ReqCallBack;

/**
 * 首页UMS请求-广告，接入UMS后台
 *
 * 2018年11月2日 15:04:23 时间原因原本需要接入UMS的广告和资讯，决定还是启用原来的9999广告后台
 *
 * @author hank
 * @since 2018-8-2
 */
public class HomeUMSAdsRequest {

    /*
     * 用户类别
     */
    public static final String USER_DEMO = "D";//模拟
    public static final String USER_REAL_N = "N";//真实N
    public static final String USER_REAL_A = "A";//真实A
    public static final String USER_GUEST = "V";//游客

    private final String TAG = "UMSAdsTag";
    private String cacheFileName = "_UMS.dat";//json保存

    public List<UMSAds> fetchLocal() {
        String str = CacheUtils.readFile(cacheFileName);
        return parse(str, false);
    }

    /**
     * @param customerType 用户类别，模拟 D，真实 N，真实 A，游客 V
     * @param callBack     回调
     */
    public void call(String customerType, final ReqCallBack<List<UMSAds>> callBack) {
        String mUrl = ConfigUtil.instance().getUrlPath("UMS_Ads");
        Log.d(TAG, "" + mUrl);
        new Https(mUrl)
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optInt(ConfigType.COMPANY_ID_TAG) + "")//公司ID 2:hx9999, 9:hxfx, 13:8bx
                .addParam("terminal", "android")//终端android
                .addParam("appId", AppMain.getApp().getPackageName())//包ID , 在终端为android,ios时必填，填包名即可
                .addParam("type", customerType)//[D:模拟客户,N:真实客户,A:激活客户,V:游客]
                .responseOnUiThread(false)
                .post(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        List<UMSAds> data = parse(result, true);
                        postSuccess(data, callBack);
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        postFailure(e, callBack);
                    }
                });
    }

    private void postSuccess(final List<UMSAds> data, final ReqCallBack<List<UMSAds>> callBack) {
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqSuccess(data);
            }
        });
    }

    private void postFailure(Exception e, final ReqCallBack<List<UMSAds>> callBack) {
        final String msg = e == null ? "" : e.getMessage();
        AppMain.getApp().getHandler().post(new Runnable() {
            @Override
            public void run() {
                callBack.onReqFailed(msg);
            }
        });
    }

    private void storeLocal(String str) {
        CacheUtils.writeFile(cacheFileName, str);
    }

    private List<UMSAds> parse(String str, boolean cache) {
        List<UMSAds> umsAdsList = new ArrayList<>();
        Log.d(TAG, "" + str);
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            if (jsonObject.optInt("ret") != 200) {
                String msg = jsonObject.optString("msg");
                Log.d(TAG, msg);
                return null;
            }
            JSONArray dataArr = jsonObject.optJSONArray("data");
            if (dataArr != null) {
                JSONObject tempO;
                for (int i = 0; i < dataArr.length(); i++) {
                    tempO = dataArr.getJSONObject(i);

                    UMSAds umsAds = new UMSAds();
                    umsAds.id = tempO.optString("id");
                    umsAds.company_id = tempO.optString("company_id");
                    umsAds.title = tempO.optString("title");
                    umsAds.terminal = tempO.optString("terminal");
                    umsAds.pic_width = tempO.optString("pic_width");
                    umsAds.pic_height = tempO.optString("pic_height");
                    umsAds.code = tempO.optString("code");
                    umsAds.comment = tempO.optString("comment");

                    //下面解析list
                    List<UMSAdsItem> umsAdsItemList = new ArrayList<>();

                    JSONArray jsonArray = tempO.optJSONArray("list");
                    JSONObject tempI;
                    for (int j = 0; j < jsonArray.length(); j++) {
                        tempI = jsonArray.getJSONObject(j);
                        UMSAdsItem tempItem = new UMSAdsItem();
                        tempItem.id = tempI.optString("id");
                        tempItem.title = tempI.getString("title");
                        tempItem.app_id = tempI.getString("app_id");
                        tempItem.jump_url = tempI.getString("jump_url");
                        tempItem.pic_url = tempI.getString("pic_url");
                        tempItem.type = tempI.getString("type");
                        tempItem.content = tempI.getString("content");
                        umsAdsItemList.add(tempItem);
                    }

                    umsAds.list = umsAdsItemList;
                    umsAdsList.add(umsAds);
                }

                if (cache) {
                    storeLocal(str);
                }
                return umsAdsList;
            }
        } catch (JSONException e) {
            Logger.e(e);
        }
        return null;
    }

    public class UMSAds {
        String id;//广告id
        String company_id;//公司ID
        String title;//广告位置名称
        String terminal;//终端
        String pic_width;//广告位置宽度
        String pic_height;//广告位置高度
        String code;//广告位置CODE
        String comment;//备注
        List<UMSAdsItem> list;//item列表
    }

    public class UMSAdsItem {
        String id;//广告ID
        String title;//广告标题
        String app_id;//包ID
        String jump_url;//广告跳转地址
        String pic_url;//广告图片地址
        String type;//适用客户类型,D,A,N,V
        String content;//内容
    }

}
